package com.budwk.app.base.gmpass;
import com.budwk.starter.common.utils.PwdUtil;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
import org.nutz.lang.Lang;

import java.util.UUID;


/**
 * 国产密码SM3算法
 * 加密字符串，加盐加密密码
 */
public class SM3Util{

    /**
     * 获取SM3加密字符串
     * @param data  加密字符串
     * @return 返回SM3加密后字符串
     */
    public static String hash1(String data){
        return Hex.toHexString(hash2(data));
    }

    /**
     * 获取SM3加密byte
     * @param data 加密字符串
     * @return 返回SM3加密byte
     */
    public static byte[] hash2(String data){
        SM3Digest sm3Digest=new SM3Digest();
        byte[] srcData = data.getBytes();
        sm3Digest.update(srcData,0,srcData.length);
        byte[] hash = new byte[sm3Digest.getDigestSize()];
        sm3Digest.doFinal(hash, 0);
        return hash;
    }

    /**
     * 密码加盐
     * @param password 密码
     * @param salt 盐
     * @return 返回加盐的密码字符串
     */
    public static String getPassword(String password, String salt) {
        byte[] bytes = hash(password.getBytes(), salt.getBytes());
        if (bytes != null) {
            return Lang.fixedHexString(bytes);
        }
        return "";
    }

    private static byte[] hash(byte[] bytes, byte[] salt) {
        try {
            //SM3计算
            byte passwdbyte[]= arrayCat(salt,bytes);
            SM3Digest mdDigest=new SM3Digest();
            mdDigest.update(passwdbyte,0,passwdbyte.length);
            byte[] result=new byte[mdDigest.getDigestSize()];
            mdDigest.doFinal(result, 0);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 组合盐与密码
     * @param buf1
     * @param buf2
     * @return
     */
    private static byte[] arrayCat(byte[] buf1,byte[] buf2) {
        byte[] bufret=null;
        int len1=0;
        int len2=0;
        if(buf1!=null)
            len1=buf1.length;
        if(buf2!=null)
            len2=buf2.length;
        if(len1+len2>0)
            bufret=new byte[len1+len2];
        if(len1>0)
            System.arraycopy(buf1,0,bufret,0,len1);
        if(len2>0)
            System.arraycopy(buf2,0,bufret,len1,len2);
        return bufret;
    }


    public static void main(String[] args) {
        SM3Util sm3 = new SM3Util();
        String data = "abcd";
        System.out.println("摘要：" + sm3.hash1(data));
        System.out.println("摘要：" + sm3.hash1("0121"+data));
        System.out.println(sm3.getPassword(data,"01111"));
        System.out.println(sm3.getPassword(data,"0121"));

        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid="+uuid);
        System.out.println("pWD:"+ PwdUtil.getPassword("1234",uuid));
        System.out.println("pWD:"+ PwdUtil.getPassword("1234"+uuid,""));
        System.out.println("pWD:"+ PwdUtil.getPassword(uuid+"1234",""));
    }
}


